<?php
/**
 * Created by PhpStorm.
 * User: spatra
 * Date: 14-11-6
 * Time: 下午4:16
 */

use \Symfony\Component\HttpFoundation\File\UploadedFile as UploadFile;

/**
 * Class PersonalController
 *
 * 此控制器用于处理用户个人的相关信息
 */
class PersonalController extends \BaseController
{
    /**
     * 构造函数，将当前用户的模型实例指向实例域currUser
     */
    public function __construct()
    {
        $this->currUser = Auth::user();
    }

    /**
     * 获取用户的基本信息
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * 返回的JSON格式如下：
     * {
     *   "username": "exampleName",
     *   "email": "example@exp.com",
     *   "head_image" : "example.png",
     *   "description: "example for describe",
     *   "identify_number": "20122004035",
     *   "role_id": "0",
     *   "role": {
     *      //具体的角色信息
     *      "id": 1,
     *      "name": "student",
     *      "label": "学生"
     *  }
     * }
     */
    public function getInfo()
    {
        $repData = $this->getSectionalValuesFromModel($this->currUser, [
            "username", "email", "head_image", "unit_id", "unit",
            "description", "identify_number", "role_id", "role"
        ]);

        return Response::json( $repData );
    }

    /**
     * 用户修改用户的基本信息.
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * 返回的JSON格式(当操作失败的时候）：
     * {
     *   "error": "错误信息",
     *   "errorMessages": {
     *     "提交的修改变量名": ['相关的错误信息']
     *   }
     * }
     */
    public function putInfo()
    {
        $putData = Input::all();

        $validator = $this->getInfoValidator($putData);

        $repData = [];
        $repStatus = 200;
        if( $validator->passes() ){
            try{$this->currUser->update($putData);
            }catch (Exception $error){
                $repData['error'] = '提交了不合法的额外数据!';
                $repStatus = 401;
            }
        } else {
            $repData['error'] = $this->changeValidatorMessageToString( $validator->messages() );
            $repStatus = 401;
        }

        return Response::json($repData, $repStatus);
    }

    /**
     * 内部使用函数，用于生成用户信息校验器.
     *
     * @param $putData
     * @return \Illuminate\Validation\Validator
     */
    protected function getInfoValidator($putData)
    {
        $verifiedRules = [
            'identify_number' => 'integer|min:0',
            'unit_id' =>'unit_check'
        ];

        Validator::extend('unit_check', function($attr, $value){
            return $value === '0' ||
            Unit::find($value);
        });

        $errorMessages = [
            'identify_number.integer' => '请输入正确格式的学号或工作号',
            'identify_number.min' => '请输入正确格式的学号或工作号'
        ];

        return Validator::make($putData, $verifiedRules, $errorMessages);
    }

    /**
     * 用于修改密码，提交的参数如下：
     *  password: 原密码
     *  newPassword:  新密码
     *  newPasswordConfirmation： 确认新密码
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * 当出错时，返回的JSON格式如下：
     * {
     *   "errorMessages" : {
     *     "password": ['相关的错误信息'],
     *     "newPassword": ['相关的错误信息'],
     *     "newPasswordConfirmation": ['相关的错误信息']
     *   }
     * }
     */
    public function putPassword()
    {
        $postData = Input::all();
        $verifiedRules = [
            'password' => 'required|check_password',
            'newPassword'=> 'required|confirmed'
        ];

        Validator::extend('check_password', function($attr, $value){
            return Auth::validate(['username'=>Auth::user()->username, 'password'=>$value] );
        });

        $errorMessage = [
            'check_password' => '原密码输入错误，请重新输入原密码',
            'confirmed' => '两次输入不一致，请重新输入'
        ];

        $validator = Validator::make($postData, $verifiedRules, $errorMessage);

        $res = [];
        $statusCode = 200;

        if ($validator->passes()) {
            User::where('id', $this->currUser->id)->update(['password'=> Hash::make( $postData['newPassword'])]);
        } else {
            $res['errorMessages'] = $validator->messages();
            $statusCode = 403;
        }
        return Response::json($res, $statusCode);
    }

    public function postHeadImage()
    {
        $validator = $this->getHeadImageValidator(Input::all());

        if( $validator->passes() ){
            $newHeadImage = $this->changeHeadImage(Input::file('file'));

            Auth::user()->update([
                'head_image'=>$newHeadImage
            ]);

            return Response::json([
               'head_image'=>$newHeadImage
            ]);
        }else{
            return Response::json([
                'error'=>$this->changeValidatorMessageToString($validator->getMessageBag())
            ], 403);
        }
    }

    protected function changeHeadImage(UploadFile $file)
    {
        $currUser = Auth::user();
        $headImageDirectory = public_path(). '/image/head_image/';

        $oldHeadImageFilePath = $headImageDirectory. $currUser['head_image'];
        if( file_exists($oldHeadImageFilePath) ){
            unlink($oldHeadImageFilePath);
        }

        $newHeadImageFileName = $currUser['username']. '-'. time(). '.'. $file->getClientOriginalExtension();

        $file->move($headImageDirectory, $newHeadImageFileName);

        return $newHeadImageFileName;
    }

    protected function getHeadImageValidator($postData)
    {
        $rules = [
          'file'=>'mimes:jpg,jpeg,png|max:1024'
        ];

        return Validator::make($postData, $rules);
    }

    private $currUser;
}